/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package cn.lg.soar.mvc.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Http与Servlet工具类.
 * @author ThinkGem
 * @version 2014-8-19
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class ServletUtils {

	public static ServletRequestAttributes getServletRequestAttributes() {
		return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes());
	}

	/**
	 * 获取当前请求对象
	 * web.xml: <listener><listener-class>
	 * 	org.springframework.web.context.request.RequestContextListener
	 * 	</listener-class></listener>
	 */
	public static HttpServletRequest getRequest(){
		return getServletRequestAttributes().getRequest();
	}

	/**
	 * 获取当前相应对象
	 * web.xml: <filter><filter-name>requestContextFilter</filter-name><filter-class>
	 * 	org.springframework.web.filter.RequestContextFilter</filter-class></filter><filter-mapping>
	 * 	<filter-name>requestContextFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
	 */
	public static HttpServletResponse getResponse(){
		return getServletRequestAttributes().getResponse();
	}

	/**
	 * 获得请求参数值
	 */
	public static String getParameter(String name) {
		return getRequest().getParameter(name);
	}

	/**
	 * 获得请求头参数值
	 */
	public static String getHeader(String name) {
		return getRequest().getHeader(name);
	}

	public static String getHeaderOrParameter(HttpServletRequest request, String name) {
		String value = request.getHeader(name);
		if (value == null) {
			value = request.getParameter(name);
		}
		return value;
	}

	public static String getHeaderOrParameter(String name) {
		return getHeaderOrParameter(getRequest(), name);
	}

}
